package com.example.cdctest.filter;

import com.example.cdctest.pojo.UserInfo;
import com.example.cdctest.service.UserInfoService;
import com.example.cdctest.util.CookieUtil;
import com.example.cdctest.util.MD5Util;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/services/*")
public class AutoLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request=(HttpServletRequest)req;
        HttpSession session=request.getSession();
        String autoLogin=(String) session.getAttribute("autoLogin");
        if (autoLogin!=null){
            chain.doFilter(req, resp);
            return;
        }else {
            session.setAttribute("autoLogin","true");
        }
        UserInfo loginUser=(UserInfo) session.getAttribute("loginUser");
        if (loginUser==null){
            String username= CookieUtil.getValue("username",request);
            String password=CookieUtil.getValue("password",request);
            if (username!=null){
                WebApplicationContext applicationContext= WebApplicationContextUtils.getWebApplicationContext(req.getServletContext());
                UserInfoService userInfoService=applicationContext.getBean("userInfoService",UserInfoService.class);
                loginUser= userInfoService.selectUserByEmail(username);
                if (loginUser!=null){
                    if (password.equals(MD5Util.mymd5(loginUser.getPassword()))){
                        session.setAttribute("loginUser",loginUser);
                    }
                }
            }
        }
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
